package com.gitee.wsl.mathematics.geometry.d3.edge

import com.gitee.wsl.mathematics.base.IsoDir
import com.gitee.wsl.mathematics.geometry.d3.face.Face
import com.gitee.wsl.mathematics.geometry.d3.vertex.Vertex
import com.gitee.wsl.mathematics.coordinate.ext.distanceToLine

data class Edge(
    val a: Vertex,
    val b: Vertex,
    val l: Face, // face to the left of the edge
    val r: Face, // face to the right of the edge
) {
    val kind: EdgeKind = EdgeKind(a.kind, b.kind, l.kind, r.kind)
    lateinit var reversed: Edge
    override fun toString(): String = "$kind edge(${a.id}-${l.id}/${r.id}-${b.id})"

    // next clockwise edge on right/left face
    fun next(dir: IsoDir): Edge = when (dir) {
        IsoDir.R -> r.directedEdges.find { it.a == b }!!
        IsoDir.L -> l.directedEdges.find { it.b == b }!!.reversed
    }
}

fun Edge.normalizedDirection(): Edge {
    val rk = kind.reversed().compareTo(kind)
    return when {
        rk < 0 -> reversed
        rk > 0 -> this
        b.id < a.id -> reversed
        else -> this
    }
}

val Edge.vec
    get() = (b - a)

val Edge.len: Double
    get() = vec.length

fun Edge.distanceTo(p: Vertex): Double =
    p.distanceToLine(a, b)

/*
fun Edge.distanceTo(p: Vec3): Double =
    p.distanceToLine(a, b)*/
